// 1. 引入各种包
const Koa = require("koa")
const KoaRouter = require("@koa/router")
const KoaStaticCache = require("koa-static-cache")
const KoaBody = require("koa-body")
const parseFilepath = require("parse-filepath")
const Mysql2 = require("mysql2")

// 2. 实例化
const app = new Koa();
const router = new KoaRouter()

// 7.连接数据库
const connection = Mysql2.createConnection({
  user:"root",
  password:"bsc123321",
  database:"kkb",
})

// 4. 静态代理
app.use(KoaStaticCache("./public",{
  prefix:'/public',
  gzip:true,
  dynamic:true,
}))
app.use(KoaStaticCache("./static",{
  prefix:'/static',
  gzip:true,
  dynamic:true,
}))


// 5. 动态资源
router.post("/upload", KoaBody({
  multipart:true,
  formidable:{
    uploadDir:'./static/upload',
    keepExtensions:true,// 保存扩展名
  }
}),async ctx => {

  // 获取文件对象
  let {attachment} = ctx.request.files;
  let index =attachment.path.lastIndexOf('/')
  let fileName = attachment.path.substring(index+1)
  let fileSize = attachment.size;
  let fileType = attachment.type;

  let res = await query('insert into `photos` (`filename`,`size`,`type`) values (?,?,?)' ,[fileName,fileSize,fileType])

  if(res.affectedRows){
    ctx.body = {msg:"上传成功",state:1,data:{name:fileName}}
  }else{
    ctx.body = {msg:"上传失败",state:0}
  }

})

router.get('/getPhotos', async ctx => {
  let imgs = await query('select * from `photos`')
  ctx.body = {msg:'成功',state:1,data:imgs}
})
app.use(router.routes())

// 3.监听端口
app.listen('8888', (e) => {
  console.log("启动成功: http://localhost:8888")
})


function query(sql,data){
  return new Promise((resolve,reject)=>{
    connection.query(sql,data,(err,...data)=>{
      if(err){
        reject(err)
      }else{
        resolve(...data)
      }
    })
  })
}